package com.wang.interceptor;

import com.wang.entity.User;
import com.wang.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AutoLoginInterceptor implements AbstractInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object arg2)throws Exception{
        Cookie[] cookies=request.getCookies();
        String username="";
        String password="";
        if (cookies !=null){
            for(int i=0;i<cookies.length;i++){
                if (cookies[i].getName().equals("user")){
                    username=cookies[i].getValue().split("==")[0];
                    password=cookies[i].getValue().split("==")[1];
                    break;
                }
            }
            if ((username!=null ||username!="")&&(password!=null ||password!="")){
                ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
                UserService userService=applicationContext.getBean("userService",UserService.class);
                User user=userService.login(username,password);
                if(user!=null){
                    request.getSession().setAttribute("user",user);
                }
            }
        }
        return true;
    }
}
